<template>
    <div class="payment-wallet">

        <div class="payment-wallet-holder">
            <h4>Wallet payment</h4>
            <p>
                <em>Balance:</em><br />
                <span>USD</span>
                <strong v-text="getPriceFormat(wallet.balance)"></strong>
                <b v-show="wallet.balance < option.amount">Insufficient balance, please recharge</b>
            </p>
            <!-- <button v-if="wallet.balance < option.amount" status="recharge" @click="doPaying()">Add funds</button> -->
            <button v-if="wallet.balance < option.amount" status="recharge" disabled>Confirm payment</button>
            <button v-else @click="doPaying()">Confirm payment</button>

            <UxLoading v-show="wallet.loading" />
        </div>

        <!-- 对话框 -->
        <UxDialog class="payment-wallet-dialog" :visible="true" :can-close="false" v-show="!!recharge.substatus"
                  :status="recharge.substatus">
            <div class="order-payment-close" @click="onClose()"><svg-icon name="dialog-close-medium" /></div>

            <!-- 输入中 -->
            <div class="order-payment-input" v-show="recharge.substatus == 'input'">
                <!-- <div class="recharge-info">
                    <figure>
                        <img src="https://img.podpartner.com/static/svgs-20230202/payment-recharge.svg" alt="">
                    </figure>
                    <p>
                        <strong v-text="'Total: USD ' + getPriceFormat(option.amount)"></strong>
                        <em v-text="'Wallet balance ' + getPriceFormat(wallet.balance)"></em>
                        <span
                            v-text="'Need to recharge: ' + getPriceFormat(Math.max(option.amount - wallet.balance, 0))"></span>
                    </p>
                </div>

                <div class="recharge-balance">
                    <label>
                        <input type="text" v-model.number="recharge.amount"
                            oninput='value=value.replace(/[^0-9.]/g,"").replace(/\.{2,}/g,".").replace(".","$#$").replace(/\./g,"").replace("$#$",".").replace(/^(\-)*(\d+)\.(\d\d).*$/,"$1$2.$3")'
                            placeholder="Recharge amount" />
                    </label>
                </div>

                <div class="recharge-notify">
                    <p v-if="rechargeForbid" v-text="rechargeForbid"></p>
                    <strong v-if="level >= 5 && !recharge_notify_ignore">
                        <span>Your POD Wallet's top-up limit has increased to USD 3,000 as your POD points reached
                            25,000.</span>
                        <a @click="setNotify()"><svg-icon name="small-close"></svg-icon></a>
                    </strong>
                </div> -->

                <div class="contact-button">
                    <div class="top-btn" @click="openWindow('https://m.me/PodPartnerCo')">
                        <img src="https://img.podpartner.com/static/images-20231130/messenger.png"
                             style="width: 18px; height: 18px" alt="" />
                        <a @click.prevent href="https://m.me/PodPartnerCo">Messenger</a>
                    </div>
                    <div class="top-btn" @click="gotoWhatsapp()">
                        <img src="https://img.podpartner.com/static/images-20231130/whatsapp-active.png"
                             style="width: 18px; height: 18px;" alt="" />
                        <a>Whatsapp</a>
                    </div>
                </div>

                <div class="recharge-payment" v-if="!!recharge.substatus" style="display: none;">
                    <h3 v-if="level >= 2">Select Payment Method</h3>
                    <OrderPaymentPaypal :disabled="rechargeForbid" :option="rechargeOption"
                                        @statusChange="rechargeStatusChange($event)" />
                    <!-- <OrderPaymentCard v-if="level >= 2" :disabled="rechargeForbid" :option="rechargeOption" @statusChange="rechargeStatusChange($event)" /> -->
                    <!-- <OrderPaymentPayoneer v-if="level >= 2" :disabled="rechargeForbid" :option="rechargeOption" @statusChange="rechargeStatusChange($event)" /> -->

                    <p>Your data is safe - we don't store <br> your card or billing method details.</p>
                </div>
            </div>

            <OrderPaymentWalletBank :bank="bank || {}" v-show="recharge.substatus == 'bank'" />

            <!-- 失败 -->
            <div class="order-payment-failure" v-show="recharge.substatus == 'failure'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-failure.png"
                         alt="">
                    <strong>Payment failed</strong>
                    <span v-text="recharge.error"></span>
                </figure>
                <button type="primary" @click="onClose()">OK</button>
            </div>

            <!-- 请求超时 -->
            <div class="order-payment-timeout" v-show="recharge.substatus == 'timeout'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/payment/order-payment-network.png"
                         alt="">
                    <strong>The connection has timed out.</strong>
                </figure>
                <button type="primary" @click="doPaying()">Try again</button>
            </div>

        </UxDialog>

    </div>

</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "OrderPaymentWallet",
    props: ["option"],
    data () {
        return {
            dialog: '', // recharge|recharging
            bank: null,
            wallet: {
                balance: 0,
                loading: true,
            },
            recharge_notify_ignore: false,
            recharge: {
                substatus: '', // input|recharge|failure|timeout
                loading: false,
                amount: 0,
                error: '',
            },
            recharge_history: []
        };
    },
    computed: {
        ...mapState('user', {
            level: "level",
        }),
        limit () {
            if (this.level >= 5) {
                return 3000;
            } else {
                return 1000;
            }
        },

        // 充值提示文案
        rechargeForbid () {
            // 是否可充值
            let value = Math.round(this.recharge.amount * 100) || 0;
            // if (value < this.option.amount - this.wallet.balance) {
            //     // 充值金额过小
            //     return "The current amount is not enough Pay Now for the order.";
            // } else

            if (value > this.limit * 100) {
                // 大于1000 美元
                return "The maximum single top-up amount is USD " + this.limit.toLocaleString();
            } else if (value < 1 * 100) {
                // 小于1 美元
                return 'The minimum top-up amount is USD 1'
            } else if (this.recharge_history.includes(value)) {
                return 'To avoid any potential bank risk control issues, You cannot top up the same amount as what you added in the past 48 hours.'
            } else {
                return false;
            }
        },
        rechargeOption () {
            return {
                payment: "wallet",
                amount: Math.round(100 * this.recharge.amount),
                action: 'recharge',
            }
        },
    },

    methods: {

        async getWallet () {
            this.wallet.loading = true;
            const response = await this.$http("Wallet.getBalance");

            if (response.code != 0) {
                this.$uxMessage.warning(response.msg)
                this.wallet.loading = false;
            } else {
                this.wallet.balance = parseInt(response.data.balance) || 0;
                this.recharge_history = response.data.recharge_list;
                this.wallet.loading = false;
            }
        },

        // 价格格式化
        getPriceFormat (val) {
            let value = parseFloat(val / 100) || 0;
            return value.toFixed(2);
        },

        // 关闭弹窗
        onClose () {
            if (this.recharge.substatus) {
                const substatus = this.recharge.substatus;
                this.recharge.substatus = ''
                this.$emit('statusChange', {
                    payment: 'wallet',
                    action: 'cancel',
                    substatus: substatus,
                    message: 'Close paying windows'
                })
            }
        },

        // 充值完成
        rechargeStatusChange (info = {}) {

            if (!this.recharge.substatus) {
                // 没有打开，不管了

            } else if (info.action == 'before') {
                // 支付前
                // 是否禁止充值
                if (this.rechargeForbid) {
                    this.$uxMessage.warning(this.rechargeForbid);
                    info.callback && info.callback(false)
                } else {
                    this.recharge.substatus = 'recharge'
                    this.recharge.error = info.message
                    info.callback && info.callback(true)
                }

            } else if (info.action == 'success') {
                // 支付成功
                // 充值成功
                // 先loading
                this.recharge.substatus = 'input'
                this.recharge.loading = true;
                this.getWallet().then((e) => {
                    // 可能充值金额不足
                    if (this.option.amount > this.wallet.balance) {
                        // 余额不足
                        // 提示余额不足，并返回到圣诞框
                        const amount = 0.01 * (this.option.amount - this.wallet.balance)
                        this.recharge.amount = parseFloat(Math.min(this.limit, Math.max(0, amount)).toFixed(2));
                        this.recharge.loading = false;
                        this.recharge.substatus = 'input'

                        this.$uxMessage.warning(
                            "Insufficient wallet balance to pay the order"
                        );
                    } else {
                        // 充值完成，其他的操作
                        this.doPaying();
                    }

                });
            } else if (info.action == 'cancel') {
                // 支付失败
                this.recharge.substatus = 'input'

            } else {
                // 其他情况不管
            }
        },

        // 开始支付
        doPaying () {

            // 设置父级状态
            const setParentStatus = (status) => {
                const parent = this.$parent.$parent;
                if (parent) {
                    parent.status = status
                }
            }

            // 钱包支付
            const payWithWallet = () => {

                // 调用支付接口
                const pay = () => {
                    const paycode = { paypal: 1, card: 2, payoneer: 3, wallet: 4 }['wallet'];

                    if (this.option.action == 'batch') {
                        // 批量支付
                        return this.$http("Order.batchPayOrder", {
                            order_code: this.option.codes,
                            payment: paycode,
                        })
                    } else {
                        //  单个支付
                        return this.$http(
                            "Order.payOrder/" + this.option.codes,
                            { payment: paycode }
                        );
                    }
                }

                setParentStatus('before')
                // 钱包直接支付
                pay().then(response => {

                    if (response.code === 400) {
                        // 超时
                        this.recharge.substatus = 'timeout'
                        setParentStatus('paying')
                    } else if (response.code === 4055) {
                        // 黑名单用户
                        this.recharge.substatus = ''
                        setParentStatus('blackuser')
                    } else if (response.code === 4001) {
                        // reload
                        this.recharge.substatus = '';
                        this.$emit('statusChange', {
                            payment: 'card',
                            action: 'reload',
                            message: response.msg
                        })

                    } else if (response.code !== 0) {
                        // 失败
                        this.recharge.substatus = 'failure';
                        this.recharge.error = response.msg
                        setParentStatus('paying')
                    } else {

                        if (response.data && response.data.state === 1) {
                            // 库存不足
                            this.recharge.substatus = '';
                            this.$emit('statusChange', {
                                payment: 'wallet',
                                action: 'stock',
                                stocks: response.data.list || [],
                                message: response.msg
                            })

                        } else {
                            // 可能是网络失败
                            this.$emit('statusChange', {
                                payment: 'wallet',
                                action: 'success',
                            })
                        }
                    }
                })

            }


            this.recharge.substatus = '';
            this.$emit('statusChange', {
                payment: 'wallet',
                action: 'before',
                callback: res => {
                    if (!res) {
                        // 不继续
                    } else if (this.wallet.balance >= this.option.amount) {
                        // 余额足够
                        payWithWallet()
                    } else {

                        this.$parent.$parent.status = 'before'
                        this.$http("Wallet.getRechargeNotify", {}).then(res => {

                            if (res.code === 0) {
                                // 有银行卡
                                // 显示银行卡信息
                                this.recharge.substatus = 'bank';
                                this.recharge.loading = false;
                                this.bank = res.data;
                                this.$parent.$parent.status = 'paying'

                            } else {
                                // 钱包余额不足
                                // 需要充值的金额
                                const amount = 0.01 * (this.option.amount - this.wallet.balance)
                                this.recharge.amount = parseFloat(Math.min(this.limit, Math.max(0, amount)).toFixed(2));
                                this.recharge.substatus = 'input';
                                this.recharge.loading = false;
                                this.$parent.$parent.status = 'paying'
                            }
                        })
                    }


                }
            })
        },

        setNotify () {
            this.recharge_notify_ignore = true;
            this.$localstoreConfig('recharge_notify_ignore', this.recharge_notify_ignore)
        },
        openWindow (url) {
            window.open(url, "_blank");
        },
        gotoWhatsapp () {
            this.$gmeRepore('whatsapp').then(e => {
                let path = "http://wa.me/message/4V7UTTIJDLJFD1"
                window.open(path, "_blank");
            })
        }
    },
    created () {
        this.getWallet()
        this.recharge_notify_ignore = this.$localstoreConfig('recharge_notify_ignore')
        this.recharge.substatus = '';
    },
    beforeDestroy () {
        this.recharge.substatus = '';
    }
};
</script>
<style lang="scss" scoped>
.payment-wallet {
    position: relative;
}

.payment-wallet-holder {
    box-sizing: border-box;
    padding: 32px 24px 36px;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    overflow: hidden;

    &>h4 {
        height: 26px;
        font-size: 18px;
        color: #000000;
        line-height: 26px;
        margin-bottom: 68px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
    }

    &>p {
        padding-top: 13px;
        position: relative;
        box-sizing: border-box;
        margin-bottom: 50px;
        padding-left: 194px;
        background: #fafafa;
        border: 1px solid #dcdcdc;
        border-radius: 8px;
        max-width: 312px;
        width: 100%;
        min-width: 280px;
        height: 64px;
        font-size: 12px;

        font-weight: normal;
        color: #919191;

        em {
            color: #555;
            margin-bottom: 2px;
            display: inline-block;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
        }

        &>span {
            font-size: 12px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #919191;
        }

        strong {
            margin-left: 4px;
            height: 20px;
            font-size: 16px;
            color: #000000;
            line-height: 20px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
        }

        b {
            position: absolute;
            left: 0;
            top: 100%;
            margin-top: 8px;
            font-size: 14px;
            color: #f44336;
            line-height: 16px;
            font-weight: normal;
        }

        &::before {
            content: '';
            display: block;
            position: absolute;
            left: 22px;
            top: 50%;
            transform: translateY(-50%);
            background-image: url('@/assets/images/payment-wallet-normal.png');
            background-size: 141px 18px;
            width: 141px;
            height: 18px;
        }

        &::after {
            content: '';
            display: block;
            width: 1px;
            height: 100%;
            background: #dcdcdc;
            position: absolute;
            left: 185px;
            top: 50%;
            transform: translateY(-50%);
        }
    }

    button {
        max-width: 312px;
        width: 100%;
        height: 48px;
        background: #ea4c89;
        border-color: transparent;
        border-radius: 8px;
        font-size: 16px;
        font-weight: bold;
        color: #ffffff;
        line-height: 18px;
        cursor: pointer;

        &:hover {
            border-color: transparent;
            background: #c94175;
        }

        &[status='recharge'] {
            background: #f6f6f6;
            border: 1px solid #e6e6e6;
            color: #919191;
            cursor: default;
        }
    }

    &>.loading {
        border-radius: 8px;
    }
}

.order-payment-input {
    display: flex;
    flex-direction: column;
    width: 348px;
    padding: 24px 18px 18px;
    margin: 0 auto;
    box-sizing: border-box;
    position: relative;

    .contact-button {
        display: flex;
        justify-content: center;
        padding-top: 120px;
        position: relative;

        &::before {
            content: 'Please contact customer service to enable this feature to complete the top-up.';
            position: absolute;
            left: 50%;
            top: 40px;
            transform: translateX(-50%);
            width: 100%;
            text-align: center;
            font-size: 14px;
        }

        .top-btn {
            &:hover {
                cursor: pointer;
                // border-color: #ea4c89;
                background: #f6f6f6;
            }

            >a {
                &:hover {
                    color: #000000 !important;
                    text-decoration: none;
                }

                color: #000000;
                margin: 0 0 0 4px;
            }

            font-size: 14px;
            color: #000000;
            box-sizing: border-box;
            height: 34px;
            background: #ffffff;
            width: 120px;
            border-radius: 8px;
            border: 1px solid #e6e6e6;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 0 12px 0;

            i {
                &:nth-child(2) {
                    color: #fbbc06;
                }

                font-size: 24px;

                &.icon-zhandianditu-kaishiliaotian {
                    color: #48c4ef;
                }

                &.icon-zhandianditu-youjian {
                    color: #f8cf1e;
                }
            }
        }

        .top-btn+.top-btn {
            margin-left: 6px;
        }
    }

    .recharge-info {
        display: flex;
        flex-direction: column;
        align-items: center;

        figure {
            width: 60px;
            height: 60px;

            svg,
            img {
                width: 100%;
                height: 100%;
            }
        }

        p {
            margin-top: 10px;
            text-align: center;

            strong {
                display: block;
                font-size: 20px;
                color: #000000;
                line-height: 24px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
            }

            em {
                display: block;
                margin-top: 26px;
                height: 16px;
                font-size: 16px;
                font-weight: normal;
                color: #f44336;
                line-height: 16px;
            }

            span {
                display: block;
                margin-top: 8px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000000;
                line-height: 16px;
            }
        }
    }

    .recharge-balance {
        display: flex;
        flex-direction: column;
        margin-top: 36px;
        position: relative;

        &>span {
            height: 18px;
            font-size: 16px;
            color: #000000;
            line-height: 18px;
        }

        label {
            height: 44px;
            background: #ffffff;
            border-radius: 8px;
            box-sizing: border-box;
            position: relative;

            &:before {
                content: 'USD';
                position: absolute;
                left: 1px;
                top: 1px;
                bottom: 1px;
                width: 56px;
                text-align: center;
                line-height: 44px;
                background: #fafafa;
                border-radius: 6px 0 0 6px;
                border-right: 1px solid #c6c6c6;
                font-size: 12px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                color: #555555;
            }

            input {
                width: 100%;
                height: 100%;
                box-sizing: border-box;
                background: #ffffff;
                color: #000;
                font-size: 14px;
                line-height: 18px;
                padding: 12px 12px 12px 68px;
                text-align: left;
                font-weight: 400;
                font-family: Roboto-Regular, Roboto;
                color: #000000;

                &::placeholder {
                    font-size: 14px;
                    color: #919191;
                }
            }
        }
    }

    .recharge-notify {
        position: relative;
        height: 98px;
        display: flex;
        flex-direction: column;

        p {
            margin-top: 8px;
            font-size: 12px;
            color: #f44336;
            line-height: 16px;
            font-family: Roboto-Regular, Roboto;
        }

        strong {
            position: relative;
            margin-top: 8px;
            box-sizing: border-box;
            background: rgba(49, 153, 189, 0.08);
            border-radius: 6px;
            display: flex;
            padding: 8px 20px 8px 12px;
            margin-top: 10px;
            font-weight: normal;
            font-family: Roboto-Regular, Roboto;

            &>span {
                font-size: 12px;
                color: #3199bd;
                line-height: 16px;
            }

            svg {
                position: absolute;
                width: 16px;
                height: 16px;
                right: 1px;
                top: 0;
                box-sizing: border-box;
                padding: 1px;
                color: #3199bd;
                cursor: pointer;

                &:hover {
                    color: #37647b;
                }
            }
        }
    }

    .recharge-payment {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;

        &>h3 {
            font-size: 14px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 16px;
            text-align: center;
        }

        &>p {
            margin-top: 12px;
            user-select: none;
            box-sizing: border-box;
            background: #f3f9f3;
            border-radius: 8px;
            padding: 14px 14px 14px 58px;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #69a274;
            line-height: 18px;
            position: relative;
            white-space: nowrap;

            &::before {
                content: '';
                display: block;
                position: absolute;
                top: 50%;
                left: 12px;
                transform: translateY(-50%);
                width: 36px;
                height: 36px;
                background-image: url('https://img.podpartner.com/static/images-20230202/payment-safe.png');
                background-size: 36px 36px;
            }
        }

        .payment-paypal,
        .payment-card,
        .payment-payoneer {
            margin-top: 12px;
        }
    }
}

.order-payment-failure,
.order-payment-timeout {
    width: 320px;
    height: 414px;
    display: flex;
    flex-direction: column;
    align-items: center;

    &>figure {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        img {
            width: 80px;
            height: 80px;
        }

        strong {
            margin: 16px 20px 0;
            font-size: 18px;
            color: #000000;
            line-height: 28px;
            text-align: center;
        }

        span {
            margin: 8px 20px;
            font-size: 14px;
            color: #555555;
            line-height: 18px;
            text-align: center;
            white-space: pre-wrap;
        }
    }

    &>button {
        height: 38px;
        line-height: 36px;
        width: 280px;
        margin-bottom: 30px;
        font-size: 14px;
    }
}

.order-payment-close {
    z-index: 1;
    position: absolute;
    right: 4px;
    top: 4px;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #555;
    transition: all 0.3s;
    cursor: pointer;
    border-radius: 4px;

    svg {
        width: 10px;
        height: 10px;
    }

    &:hover {
        background-color: rgba(255, 0, 0, 0.1);
        color: #8c1c14;
    }
}

.payment-wallet-dialog {
    &[status='recharge'] {
        display: none !important;
        pointer-events: none;
    }

    &::v-deep>.dialog-content>h6 {
        display: none;
    }
}
</style>
